import Component from '@glimmer/component';
import { tracked } from '@glimmer/tracking';
import { action } from '@ember/object';
import { service } from '@ember/service';

export default class TMapComponent extends Component {
  @service call;
  @service message;

  @tracked showModal = false;

  constructor() {
    super(...arguments);
    // 获取地图apikey
    this.call.getCached('/api/config/amap.KeyAndCode').then((res) => {
      if (res.success) {
        var data = JSON.parse(res.data.value);
        this.amapKey = data.amapKey;
      }
    });
  }

  @action
  closeMapModal() {
    this.showModal = false;
  }

  @action
  loadMap() {
    if (this.longitude.value && this.latitude.value) {
      this.doOpenMap({
        longitude: this.longitude.value,
        latitude: this.latitude.value,
      });
      return;
    }

    // 没有经纬度,使用城市经纬度
    var city = document.querySelector(
      'input[form="' + this.args.form + '"][name="city"]',
    );
    var province = document.querySelector(
      'input[form="' + this.args.form + '"][name="province"]',
    );
    if (!city.value || !province.value) {
      this.message.showErrMsg('请先选择城市');
      return;
    }

    this.call
      .getCached(
        '/api/configSingle/area.city.' + province.value + '?id=' + city.value,
      )
      .then((res) => {
        if (res.success) {
          var data = JSON.parse(res.data.value);
          this.doOpenMap(data);
        } else {
          this.message.showErrMsg('获取城市经纬度失败');
        }
      });
  }

  doOpenMap(data) {
    this.mapIframe.src =
      'https://m.amap.com/picker/?keywords=景点,酒店,餐饮&center=' +
      data.longitude +
      ',' +
      data.latitude +
      '&radius=100000&' +
      this.amapKey;
    this.showModal = true;

    var iframe = this.mapIframe.contentWindow;
    this.mapIframe.onload = function () {
      iframe.postMessage('hello', 'https://m.amap.com/picker/');
    };
    window.addEventListener('message', this.closeEvent, false);
  }

  closeEvent = (e) => {
    var showText = document.querySelector(
      'input[form="' + this.args.form + '"][name="detail"]',
    );
    showText.value = e.data.name;
    this.longitude.value = e.data.location.split(',')[0];
    this.latitude.value = e.data.location.split(',')[1];
    this.showModal = false;
  };
}
